﻿using AntUnion.FrameWork.Model.Models;
using AntUnion.FrameWork.Util;
using AntUnion.FrameWork.Web.Service;
using MetaQuotes.MT5WebAPI.Common;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace AntUnion.FrameWork.Web.Areas.Console.Controllers
{
    public class CashVerificationController : BaseController
    {
        private readonly IWebHostEnvironment _hostingEnv;
        private readonly mtContext _context;

        public CashVerificationController(mtContext context, IWebHostEnvironment hostingEnv) : base(context, hostingEnv)
        {
            _context = context;
            _hostingEnv = hostingEnv;
        }

        #region 列表
        public IActionResult Index()
        {
            return View();
        }
        [HttpGet]
        public async Task<JsonResult> GetListJson(int page, int limit, string account, string createDate, long login, string orderNo, string Reviewer, int Mothod = -1, int state = -1)
        {
            ListResult res = new ListResult();
            try
            {
                var data = from y in _context.CrmWithdrawals
                           join c in _context.CrmUsers on y.CrmId equals c.Id
                           join d in _context.Mt5Users on c.Id equals d.CrmId
                           select new
                           {
                               index = y.Id,
                               fullName = c.Name,
                               loginName = c.LoginName,
                               paymentMethod = y.Mothod,
                               cashOutAccount = y.Login,
                               state = y.State,
                               paymentAmount = y.FromAmount == 0 ? "0.00" : ((decimal)y.FromAmount).ToString("#,##0.00"),
                               commission = y.Fees == 0 ? "0.00" : ((decimal)y.Fees).ToString("#,##0.00"),
                               receivedAmount = y.WithdrawalAmount == 0 ? "0.00" : ((decimal)y.WithdrawalAmount).ToString("#,##0.00"),
                               createDate = y.CreateDate,
                               currentReviewer = y.Reviewer,
                               endTime = y.OverDate,
                               orderNumber = y.Id,
                               tradingAccount = d.Login

                           };
                //姓/名/账户ID
                if (!string.IsNullOrEmpty(account))
                {
                    long loginNo = 0;
                    try
                    {
                        loginNo = Convert.ToInt64(account);
                    }
                    catch
                    {
                        loginNo = 0;
                    }
                    if (loginNo == 0)
                    {
                        data = data.Where(k => k.loginName.Contains(account) || k.fullName.Contains(account));
                    }
                    else
                    {
                        data = data.Where(k => k.loginName.Contains(account) || k.fullName.Contains(account) || k.tradingAccount == loginNo);
                    }
                }
                //出金账户
                if (login > 0)
                {
                    data = data.Where(k => k.cashOutAccount == login);
                }
                //订单号
                if (!string.IsNullOrEmpty(orderNo))
                {
                    data = data.Where(k => k.orderNumber == orderNo);
                }
                //出金方式
                if (Mothod > -1)
                {
                    data = data.Where(k => k.paymentMethod == Mothod);
                }
                //状态
                if (state > -1)
                {
                    data = data.Where(k => k.state == state);
                }
                //创建时间
                if (!string.IsNullOrEmpty(createDate) && createDate.Contains(" - "))
                {
                    string[] createDates = createDate.Split(new string[] { " - " }, StringSplitOptions.None);
                    DateTime startTime = Convert.ToDateTime(createDates[0]);
                    DateTime endTime = Convert.ToDateTime(createDates[1]);
                    data = data.Where(k => k.createDate > startTime && k.createDate < endTime);
                }
                //审核人
                if (!string.IsNullOrEmpty(Reviewer))
                {
                    data = data.Where(k => k.currentReviewer == Reviewer);
                }
                res.Count = data.Count();
                res.Data = await data.OrderBy(k => k.state).ThenByDescending(k => k.createDate).ThenByDescending(k => k.endTime).Skip((page - 1) * limit).Take(limit).ToArrayAsync();
                res.Code = 0;
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }
        #endregion

        #region 出金审核
        public async Task<IActionResult> CashVerificationDetail(string id)
        {
            #region 获取出金信息          
            CrmWithdrawal crmWithdrawal = await _context.CrmWithdrawals.FindAsync(id);

            if (crmWithdrawal == null)
            {
                return NotFound();
            }
            ViewBag.paymentAmount = crmWithdrawal.FromAmount == 0 ? "0.00" : ((decimal)crmWithdrawal.FromAmount).ToString("#,##0.00");
            ViewBag.commission = crmWithdrawal.Fees == 0 ? "0.00" : ((decimal)crmWithdrawal.Fees).ToString("#,##0.00");
            ViewBag.exchangeRate = crmWithdrawal.ExchangeRate == 0 ? "0.00" : ((decimal)crmWithdrawal.ExchangeRate).ToString("#,##0.00");
            ViewBag.receivedAmount = crmWithdrawal.WithdrawalAmount == 0 ? "0.00" : ((decimal)crmWithdrawal.WithdrawalAmount).ToString("#,##0.00");
            #endregion

            #region 获取用户信息
            CrmUser crmUser = await _context.CrmUsers.FindAsync(crmWithdrawal.CrmId);
            if (crmUser == null)
            {
                return NotFound();
            }
            ViewBag.crmUsers = crmUser;
            #endregion

            #region 获取钱包信息
            if (crmWithdrawal.Account != null)
            {
                if (crmWithdrawal.Mothod == 1)
                {

                    CrmWireTransfer crmWireTransfer = JsonUtil.DeserializeJsonToObject<CrmWireTransfer>(crmWithdrawal.Account);
                    ViewBag.crmWireTransfer = crmWireTransfer;
                }
                else if (crmWithdrawal.Mothod == 2)
                {
                    CrmRemittanceAccount crmRemittanceAccount = JsonUtil.DeserializeJsonToObject<CrmRemittanceAccount>(crmWithdrawal.Account);
                    ViewBag.crmRemittanceAccount = crmRemittanceAccount;
                }
                else
                {
                    CrmCryptocurrency crmCryptocurrency = JsonUtil.DeserializeJsonToObject<CrmCryptocurrency>(crmWithdrawal.Account);
                    ViewBag.crmCryptocurrency = crmCryptocurrency;
                }
            }
            #endregion

            #region 审核记录

            var data = from y in _context.CrmAuditLogs
                       join c in _context.TbUsers on y.ReviewerId equals c.Id into cc
                       from ccdata in cc.DefaultIfEmpty()
                       join d in _context.CrmUsers on y.CrmId equals d.Id
                       select new CrmAuditLog
                       {
                           Id = y.Id,
                           OrderId = y.OrderId,
                           CrmId = y.CrmId,
                           Type = y.Type,
                           Cont = y.Cont,
                           Remark = y.Remark,
                           Reviewer = y.ReviewerId != null ? ccdata.UserName : d.Name,
                           CreateDate = y.CreateDate,
                           ReviewerId = y.ReviewerId

                       };
            var crmAuditLogs = data.Where(k => k.OrderId == crmWithdrawal.Id.ToString() && k.Type == 5).OrderBy(p => p.Id).ToList();
            ViewBag.crmAuditLogsList = crmAuditLogs;
            #endregion

            #region 登录用户名
            ViewBag.LoginName = User.UserName;
            #endregion

            return View(crmWithdrawal);
        }
        #endregion

        #region 保存审核信息
        [HttpPost]
        public async Task<JsonResult> Edit(string Id, int State, string Remarks, double Toamount)
        {
            Result res = new Result();
            try
            {
                CrmWithdrawal crmWithdrawal = await _context.CrmWithdrawals.FindAsync(Id);
                MT5CommonHelper mT5CommonHelper = new MT5CommonHelper();
                Mt5User mt5User = new Mt5User();
                ulong ticker = 0;
                if (crmWithdrawal == null)
                {
                    res.Code = 1;
                    res.Msg = "getUserDetailsFail";
                    return new JsonResult(res);
                }
                if (crmWithdrawal.FromAmount <= 0)
                {
                    res.Code = 1;
                    res.Msg = "incorrectSmountOfDeposit";
                    return new JsonResult(res);
                }

                #region 判断是否有服务器可用 
                Mt5Server mt5Server = _context.Mt5Servers.Where(k => k.State == 1 && k.Type == 1).OrderByDescending(k => k.Default).ThenBy(k => k.Sort).FirstOrDefault();
                if (mt5Server == null)
                {
                    res.Code = 1;
                    res.Msg = "warningMt5";
                    return new JsonResult(res);
                }
                #endregion

                #region 判断状态是否改变
                if (crmWithdrawal.State != 0)
                {
                    res.Code = 1;
                    res.Msg = "warningUser";
                    return new JsonResult(res);
                }
                #endregion

                #region 判断是否扣款

                double FromAmount = Convert.ToDouble(crmWithdrawal.FromAmount);
                double fees = FromAmount - Toamount;
                if (State == 2)
                {
                    #region 修改MT5用户表数据          
                    mt5User = _context.Mt5Users.Where(k => k.Login == crmWithdrawal.Login).FirstOrDefault();
                    if (mt5User != null)
                    {
                        MTUser tmu = mT5CommonHelper.QueryUsers(Convert.ToUInt64(crmWithdrawal.Login));
                        mt5User.Balance = Convert.ToDecimal(tmu.Balance);
                    }

                    #endregion
                    #region 修改审核流水信息
                    Mt5Transaction mt5Transaction = _context.Mt5Transactions.Where(k => k.OrderId == crmWithdrawal.Mt5Order).FirstOrDefault();
                    if (mt5Transaction != null)
                    {
                        mt5Transaction.Fees = Convert.ToDecimal(fees);
                        mt5Transaction.Toamount = Convert.ToDecimal(Toamount);

                    }

                    #endregion
                }
                else
                {
                    bool MTRetCode = mT5CommonHelper.TradeBalance(_context, Convert.ToUInt64(crmWithdrawal.Login), MTDeal.EnDealAction.DEAL_BALANCE, "withdrawalRefund", FromAmount, crmWithdrawal.Remark, Toamount, Convert.ToDecimal(fees), User.LoginName, out ticker);
                    if (!MTRetCode)
                    {
                        res.Code = 1;
                        res.Msg = "withdrawalFailed";
                        return new JsonResult(res);
                    }
                    else
                    {
                        #region 修改MT5用户表数据          
                        mt5User = _context.Mt5Users.Where(k => k.Login == crmWithdrawal.Login).FirstOrDefault();
                        if (mt5User != null)
                        {
                            MTUser tmu = mT5CommonHelper.QueryUsers(Convert.ToUInt64(crmWithdrawal.Login));
                            mt5User.Balance = Convert.ToDecimal(tmu.Balance);
                            mt5User.UpdateDate = DateTime.Now;
                        }
                        #endregion
                    }
                }

                #endregion

                #region 修改出金记录表
                crmWithdrawal.State = State;
                //crmWithdrawal.Remark = Remarks;
                crmWithdrawal.Reviewer = User.UserName;
                crmWithdrawal.OverDate = DateTimeUtil.Now;
                //crmWithdrawal.Mt5Order = ticker.ToString();
                crmWithdrawal.Fees = Convert.ToDecimal(fees);
                crmWithdrawal.WithdrawalAmount = Convert.ToDecimal(Toamount);
                #endregion

                #region 新增审核记录
                CrmAuditLog crmAuditLog = new CrmAuditLog();
                crmAuditLog.OrderId = crmWithdrawal.Id.ToString();
                crmAuditLog.CrmId = crmWithdrawal.CrmId;
                crmAuditLog.Type = 5;
                if (State == 2)
                    crmAuditLog.Cont = "审核通过";
                else
                    crmAuditLog.Cont = "审核拒绝";
                crmAuditLog.Reviewer = User.UserName;
                crmAuditLog.Remark = Remarks;
                crmAuditLog.ReviewerId = User.Id;
                crmAuditLog.CreateDate = DateTimeUtil.Now;
                _context.Add(crmAuditLog);
                #endregion

                res.Code = 0;
                res.Data = await _context.SaveChangesAsync();
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);

            }
        }
        #endregion

    }
}
